package cn.ainit.base.product;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.junit.Test;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.ainit.base.product.entity.ProductInfo;
import cn.ainit.sys.common.dao.BusinessBaseDao;
@Transactional
@Repository("productDao")
public class ProductDaoImpl extends BusinessBaseDao implements ProductDao {

	@Override
	public boolean saveProduct(ProductInfo productInfo) throws Exception {
		try {
			this.getSessionFactory().getCurrentSession().save(productInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public boolean updProduct(ProductInfo productInfo) throws Exception {
		try {
			this.getSessionFactory().getCurrentSession().update(productInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	@Override
	public boolean findProduct(String hid) throws Exception {
		try {
			ProductInfo productInfo = (ProductInfo) this.getSessionFactory().getCurrentSession().get(ProductInfo.class, hid);
			if (productInfo == null) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	@Override
	public List xtFindProd(String isbns) throws Exception {
		try {
			List products=new ArrayList();
			Object[] isbn = isbns.split(";");
			String oneIsbn = "";
			for(int i = 0 ; i < isbn.length; i ++){
				oneIsbn+= "'"+isbn[i].toString()+"'";
				if (i<isbn.length -1 ) {
					oneIsbn+= ",";
				}
			}
			String sql = "select p.h_id,p.h_isbn,p.h_name from bs_product p where p.h_isbn in ("+oneIsbn+")";
			products = this.getJdbcTemplate().queryForList(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public String execProFunc(String proId,String staId,String oid) throws Exception {
		String proStockNum="";
		Connection conn = null;
		CallableStatement cs = null;
		try {
			 conn =  this.getJdbcTemplate().getDataSource().getConnection();
			 String sql = "{?=call PK_FX.uf_StockNum(?,?,?)}";
			 cs = conn.prepareCall(sql);
			 cs.registerOutParameter(1, Types.VARCHAR); 
			 cs.setString(2,proId);
			 cs.setString(3,staId);
			 cs.setString(4,oid);
			 cs.execute();
			 proStockNum = cs.getString(1);  
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(cs != null){
				cs.close();
			}
			if(conn != null){
				conn.close();
			}
		}
		return proStockNum;
	}
	
}
 